const Service = require('egg').Service;
const jwt = require('jsonwebtoken')
const { md5 } = require('utility')

class HomeService extends Service {
    async login() {
        const { ctx, app } = this;
        const { username} = ctx.request.body
        const isHave = await app.mysql.get('users', { username })
        if (isHave) {
            return {
                data: isHave,
                token: jwt.sign({ ...isHave }, app.config.keys)
            }
        } else {
            return '账号密码有误'
        }
    }

    async register() {
        const { ctx, app } = this;
        const { username, password, nickname } = ctx.request.body
        const isHave = await app.mysql.get('users', { username })
        if (isHave) {
            return '账号已存在'
        } else {
            const data = await app.mysql.insert('users', { username, password: md5(String(password)), nickname })
            return data
        }
    }
}

module.exports = HomeService;